<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>用户登录</h2>
      </div>
      <van-cell-group class="cell-group">
        <van-field label="账号" placeholder="请输入账号" v-model="loginForm.name" class="login-field"
          :placeholder-style="{ color: '#ccc' }" />
        <van-field label="密码" placeholder="请输入密码" type="password" v-model="loginForm.password"
          class="login-field" :placeholder-style="{ color: '#ccc' }">
          <template #button>
            <van-button 
              class="forgot-password-btn" 
              @click="goToRePassword"
            >
              忘记密码
            </van-button>
          </template>
        </van-field>
        <van-button @click="onClickLogin" type="primary" size="normal" block class="login-button"
          :loading="isLoading">
          {{ isLoading? '登录中...' : '登录' }}
        </van-button>
      </van-cell-group>
      <div class="other-login-options">
        <van-button @click="goToCaptchaLogin" class="other-login-btn">
          验证码登录
        </van-button>
        <van-button @click="onThirdLogin" class="other-login-btn">
          第三方登录
        </van-button>
      </div>
      <div class="goto">
        <van-button @click="onRegister" class="register-link">
          若还没有账号？点击前往注册
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { showToast } from 'vant';
import { getUserLocal, setUserLocal, setTokenLocal } from "@/utils/auth.js";
import { loginAPI } from "@/api/user.js";

export default {
  data() {
    return {
      loginForm: {
        name: "",
        password: ""
      },
      isLoading: false
    };
  },

  mounted() {
    const user = getUserLocal();
    if (user) {
      this.loginForm.name = user.name || ""; // 避免name字段缺失导致错误
    }
  },

  methods: {
    // 重试请求函数
    async retryRequest(requestFunction, maxRetries = 3) {
      let retries = 0;
      while (retries < maxRetries) {
        try {
          return await requestFunction();
        } catch (error) {
          retries++;
          if (retries === maxRetries) {
            throw error;
          }
          console.log(`请求失败，正在进行第 ${retries} 次重试...`);
        }
      }
    },

    // 处理用户登录
    async onClickLogin() {
      // 验证用户名和密码长度
      if (this.loginForm.name.length < 3 || this.loginForm.name.length > 20) {
        showToast("用户名长度必须在 3 到 20 个字符之间");
        return;
      }
      if (this.loginForm.password.length < 6 || this.loginForm.password.length > 30) {
        showToast("密码长度必须在 6 到 30 个字符之间");
        return;
      }

      this.isLoading = true;
      const params = this.loginForm;
      try {
        const result = await this.retryRequest(() => loginAPI(params));
        
        // 验证接口返回数据有效性
        if (!result?.data) {
          throw new Error("登录数据格式错误");
        }

        // 存储Token
        setTokenLocal(result.data.token);

        // 组装并校验用户信息（核心修复点：使用组装的有效对象）
        const user = {
          id: result.data.id,
          name: result.data.name,
          avatar: result.data.avatar || "" // 允许头像为空，避免字段缺失
        };
        // 校验必要字段（id和name为必填）
        if (!user.id || !user.name) {
          throw new Error("用户信息不完整");
        }
        setUserLocal(user); // 存储有效用户对象

        // 登录成功提示与跳转
        showToast({
          message: "登录成功！",
          duration: 1000
        });
        const toPath = this.$route.params.redirect || "user";
        setTimeout(() => {
          this.$router.replace({ path: toPath });
        }, 1000);

      } catch (error) {
        // 错误提示细化
        const errorMsg = error.message.includes("用户名或密码") 
          ? "用户名或密码错误，请重新输入"
          : error.message.includes("用户信息")
            ? "用户信息异常，登录失败"
            : "登录失败，请稍后重试";
        showToast(errorMsg);
        console.error('登录错误:', error);
      } finally {
        this.isLoading = false;
      }
    },

    // 跳转到忘记密码页面
    goToRePassword() {
      this.$router.push({ name: 'forgotPassword' });
    },
    
    // 跳转到验证码登录页面
    goToCaptchaLogin() {
      this.$router.push({ name: "captchaLogin" });
    },
    
    // 处理第三方登录
    onThirdLogin() {
      this.$router.push({ name: 'thirdLogin' });
    },
    
    // 处理用户注册
    onRegister() {
      this.$router.push({ name: "register" });
    }
  }
};
</script>

<style lang="less" scoped>
  @bg-color: #f9f9f9;
  @primary-color: #007bff;
  @secondary-color: #f0f0f0;
  @text-color: #333;
  @link-color: #007bff;
  @border-color: #e0e0e0;

  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: @bg-color;
    animation: fadeIn 1s ease;
  }

  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }

  .login-box {
    width: 350px;
    padding: 30px;
    background-color: #fff;
    border-radius: 15px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
    animation: slideIn 1s ease;
  }

  @keyframes slideIn {
    from { transform: translateY(-50px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
  }

  .login-header {
    text-align: center;
    margin-bottom: 25px;
  }

  .login-header h2 {
    font-size: 28px;
    color: @text-color;
    font-weight: bold;
  }

  .cell-group {
    border: 1px solid @border-color;
    border-radius: 10px;
    padding: 20px;
  }

  .login-field {
    margin-bottom: 20px;
    border: none;
    border-bottom: 2px solid @secondary-color;
    padding-bottom: 10px;
    font-size: 16px;
    color: @text-color;
    transition: border-bottom-color 0.3s ease;

    &:focus {
      border-bottom-color: @primary-color;
    }
  }

  .login-button {
    margin-top: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    padding: 12px;
    font-size: 18px;
    transition: all 0.3s ease;

    &:hover {
      background-color: darken(@primary-color, 10%);
      transform: translateY(-3px);
      box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
    }
  }

  .goto {
    margin-top: 20px;
    text-align: center;
    font-size: 14px;
    color: @text-color;
  }

  .register-link {
    color: @link-color;
    text-decoration: underline;
    transition: all 0.3s ease;
    border: none;

    &:hover {
      color: darken(@link-color, 10%);
    }
  }

  .other-login-options {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
  }
  
  .other-login-btn {
    border: none;
    background: transparent;
    color: @link-color;
    text-decoration: underline;
    
    &:hover {
      color: darken(@link-color, 10%);
    }
  }

  .forgot-password-btn {
    color: @link-color;
    font-size: 14px;
    padding: 0;
    border: none;
    
    &:hover {
      color: darken(@link-color, 10%);
      text-decoration: underline;
    }
  }
</style>